package cc.mrbird.febs.system.controller;

import cc.mrbird.febs.common.authentication.ShiroHelper;
import cc.mrbird.febs.common.controller.BaseController;
import cc.mrbird.febs.common.entity.FebsConstant;
import cc.mrbird.febs.common.exception.FebsException;
import cc.mrbird.febs.common.utils.DateUtil;
import cc.mrbird.febs.common.utils.FebsUtil;
import cc.mrbird.febs.common.utils.IntegerUtils;
import cc.mrbird.febs.system.entity.*;
import cc.mrbird.febs.system.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.ExpiredSessionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author MrBird
 */
@Controller("systemView")
public class ViewController extends BaseController {

    @Autowired
    private IUserService userService;

    @Autowired
    private ShiroHelper shiroHelper;

    @Resource
    private IUserDeptService userDeptService;

    @Resource
    private ICourseService courseService;

    @Resource
    private IDeptService deptService;

    @Autowired
    private IExperimentProjectService iExperimentProjectService;
    @GetMapping("login")
    @ResponseBody
    public Object login(HttpServletRequest request) {
        if (FebsUtil.isAjaxRequest(request)) {
            throw new ExpiredSessionException();
        } else {
            ModelAndView mav = new ModelAndView();
            mav.setViewName(FebsUtil.view("login"));
            return mav;
        }
    }

    @GetMapping("unauthorized")
    public String unauthorized() {
        return FebsUtil.view("error/403");
    }


    @GetMapping("/")
    public String redirectIndex() {
        return "redirect:/index";
    }

    @GetMapping("index")
    public String index(Model model) {
        AuthorizationInfo authorizationInfo = shiroHelper.getCurrentuserAuthorizationInfo();
        User user = super.getCurrentUser();
        User currentUserDetail = userService.findByName(user.getUsername());
        currentUserDetail.setPassword("It's a secret");
        model.addAttribute("user", currentUserDetail);
        model.addAttribute("permissions", authorizationInfo.getStringPermissions());
        model.addAttribute("roles", authorizationInfo.getRoles());
        return "index";
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "layout")
    public String layout() {
        return FebsUtil.view("layout");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "password/update")
    public String passwordUpdate() {
        return FebsUtil.view("system/user/passwordUpdate");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "user/profile")
    public String userProfile() {
        return FebsUtil.view("system/user/userProfile");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "user/avatar")
    public String userAvatar() {
        return FebsUtil.view("system/user/avatar");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "user/profile/update")
    public String profileUpdate() {
        return FebsUtil.view("system/user/profileUpdate");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/user")
    @RequiresPermissions("user:view")
    public String systemUser() {
        return FebsUtil.view("system/user/user");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/userTeacher")
    @RequiresPermissions("user:view")
    public String systemUserTeacher() {
        return FebsUtil.view("system/user/userTeacher");
    }


    @GetMapping(FebsConstant.VIEW_PREFIX + "system/user/add")
    @RequiresPermissions("user:add")
    public String systemUserAdd() {
        return FebsUtil.view("system/user/userAdd");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/user/detail/{username}")
    @RequiresPermissions("user:view")
    public String systemUserDetail(@PathVariable String username, Model model) {
        resolveUserModel(username, model, true);
        return FebsUtil.view("system/user/userDetail");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/user/update/{username}")
    @RequiresPermissions("user:update")
    public String systemUserUpdate(@PathVariable String username, Model model) {
        resolveUserModel(username, model, false);
        return FebsUtil.view("system/user/userUpdate");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/role")
    @RequiresPermissions("role:view")
    public String systemRole() {
        return FebsUtil.view("system/role/role");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/menu")
    @RequiresPermissions("menu:view")
    public String systemMenu() {
        return FebsUtil.view("system/menu/menu");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/dept")
    @RequiresPermissions("dept:view")
    public String systemDept() {
        return FebsUtil.view("system/dept/dept");
    }

    @RequestMapping(FebsConstant.VIEW_PREFIX + "index")
    public String pageIndex() {
        return FebsUtil.view("index");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "404")
    public String error404() {
        return FebsUtil.view("error/404");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "403")
    public String error403() {
        return FebsUtil.view("error/403");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "500")
    public String error500() {
        return FebsUtil.view("error/500");
    }

    private void resolveUserModel(String username, Model model, Boolean transform) {
        User user = userService.findByName(username);
        List<Integer> deptIdList = new ArrayList<>();
        List<UserDept> userDeptList = userDeptService.list(new QueryWrapper<UserDept>().lambda().eq(UserDept::getUserId, user.getUserId()));
        for (UserDept userDept : userDeptList) {
            deptIdList.add(userDept.getDeptId());
        }
        user.setDeptIds(deptIdList);
        model.addAttribute("user", user);
        if (transform) {
            String ssex = user.getSex();
            if (User.SEX_MALE.equals(ssex)) {
                user.setSex("男");
            } else if (User.SEX_FEMALE.equals(ssex)) {
                user.setSex("女");
            } else {
                user.setSex("保密");
            }
        }
        if (user.getLastLoginTime() != null) {
            model.addAttribute("lastLoginTime", DateUtil.getDateFormat(user.getLastLoginTime(), DateUtil.FULL_TIME_SPLIT_PATTERN));
        }
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/course")
    @RequiresPermissions("course:view")
    public String systemCourse() {
        return FebsUtil.view("system/course/course");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/course/add")
    @RequiresPermissions("course:add")
    public String systemCourseAdd() {
        return FebsUtil.view("system/course/courseAdd");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/course/update/{courseId}")
    @RequiresPermissions("course:update")
    public String systemCourseUpdate(@PathVariable Integer courseId,Model model) {
        Course course = courseService.getById(courseId);
        model.addAttribute("course",course);
        System.out.println("course------------"+course);
        return FebsUtil.view("system/course/courseUpdate");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/course/view/{courseId}")
    @RequiresPermissions("course:update")
    public String systemCourseView(@PathVariable Integer courseId,Model model) {
        Course course = courseService.getById(courseId);
        String s = DateUtil.formatFullTime(course.getCreateTime(), DateUtil.FULL_TIME_SPLIT_PATTERN);
        course.setCreateTimes(s);
        model.addAttribute("course",course);
        return FebsUtil.view("system/course/courseView");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/experiment")
    @RequiresPermissions("experiment:view")
    public String systemExperiment() {
        return FebsUtil.view("system/experiment/experiment");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/experiment/add")
    @RequiresPermissions("experiment:add")
    public String systemExperimentAdd() {
        return FebsUtil.view("system/experiment/experimentAdd");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/experiment/project")
    @RequiresPermissions("experimentProject:view")
    public String systemExperimentProject() {
        return FebsUtil.view("system/experiment/project/project");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "system/experiment/project/add")
    @RequiresPermissions("experimentProject:add")
    public String systemExperimentProjectAdd() {
        return FebsUtil.view("system/experiment/project/projectAdd");
    }



    /**
    * GuiYongkang
    * 2020/4/01
    * 项目管理 实验项目模块中 查看单个实验项目详情页面的跳转
    */
    @GetMapping(FebsConstant.VIEW_PREFIX + "system/experiment/project/view/{projectId}")
    @RequiresPermissions("experimentProject:view")
    public String systemExperimentProjectView(@PathVariable Long projectId,Model model) {
        System.out.println(projectId);
        ExperimentProject project = iExperimentProjectService.getById(projectId);
        model.addAttribute("project",project);
        return FebsUtil.view("system/experiment/project/projectView");
    }

    /**
     * GuiYongkang
     * 2020/4/01 14:19pm
     * 项目管理 实验项目模块中  修改单个实验项目详情页面的跳转
     */
    @GetMapping(FebsConstant.VIEW_PREFIX + "system/experiment/project/update/{projectId}")
    @RequiresPermissions("experimentProject:update")
    public String systemExperimentProjectUpdate(@PathVariable Long projectId,Model model) {
        System.out.println(projectId);
        ExperimentProject project = iExperimentProjectService.getById(projectId);
        model.addAttribute("project",project);
        return FebsUtil.view("system/experiment/project/projectUpdate");
    }







}
